<script lang='ts' setup>
import { searchToJson } from "@/utils/common.methods";
import { ref, defineProps, onMounted } from "vue";
import { encode, decode } from "js-base64"; // 直接使用即可
const text = ref("");
const result = ref("");

onMounted(() => {
  let search = location.search.split("?")[1];
  search = unescape(search);
  if (search) {
    text.value = decode(searchToJson<{ text: string }>(search)?.text);
    if (text.value) onPretty();
  }
});

/** 美化 */
function onPretty(): void {
  result.value = prettyFormat(text.value);
}

function prettyFormat(str: string) {
  try {
    // 设置缩进为2个空格
    str = JSON.stringify(JSON.parse(str), null, 2);
    str = str
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;");
    return str.replace(
      /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
      function (match) {
        var cls = "number";
        if (/^"/.test(match)) {
          if (/:$/.test(match)) {
            cls = "key";
          } else {
            cls = "string";
          }
        } else if (/true|false/.test(match)) {
          cls = "boolean";
        } else if (/null/.test(match)) {
          cls = "null";
        }
        return match;
      }
    );
  } catch (e) {
    console.error("异常信息:" + e);
    return "异常，原文非json";
  }
}
</script>
<template>
  <div class="json">
    <div class="title hr">在线 JSON 美化</div>
    <div class="box">
      <div class="sub-title">请输入要进行美化的 json</div>
      <t-textarea placeholder="请输入内容" :autosize="{ minRows: 5, maxRows: 10 }" v-model="text" />
    </div>
    <div class="btns flex">
      <t-button class="btn" :disabled="!text" @click="onPretty">美化 (Pretty)</t-button>
    </div>
    <div class="box">
      <div class="sub-title">结果：</div>
      <t-textarea placeholder="请输入内容" :autosize="{ minRows: 5, maxRows: 10 }" v-model="result" />
    </div>
  </div>
</template>
<style lang='scss' scoped>
.json {
  padding: 40px;
  width: 100%;

  .title {
    font-size: 25px;
  }

  .box {
    margin: 10px 0;

    .sub-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 10px;
    }
  }

  .btns {
    .btn {
      margin-right: 10px;
    }
  }
}</style>